import { Component, OnInit, ViewChild, TemplateRef, Input } from '@angular/core';
import _ from 'lodash';
import { MySelection } from 'app/modules/base/selection';
import { Zone } from 'app/modules/zone/services/zone.service';
import { SoftwareService, SoftwareInfo } from 'app/modules/software/services/software.service';
import { MatDialog } from '@angular/material';
import { ReplaySubject } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';
import { StatisticService } from '../../services/statistic.service';
import { EchartsComponent } from 'app/modules/share/components/echarts/echarts.component';
import { LoginService } from 'app/modules/login/services/login.service';
import { EChartOptionExp } from 'app/modules/share/components/status-card/e-chart-option-exp.module';

const StoreKey = 'software_usage';

@Component({
  selector: 'm-software-usage',
  templateUrl: './software-usage.component.html',
  styleUrls: ['./software-usage.component.scss'],
})
export class SoftwareUsageComponent implements OnInit {
  constructor(
    private loginService: LoginService,
    private statisticService: StatisticService,
    public dialog: MatDialog,
    public softwareService: SoftwareService,
  ) {}
  @Input() zone: Zone;
  @ViewChild(EchartsComponent) chart: EchartsComponent;
  @ViewChild('softwareSelect') softwareSelect: TemplateRef<any>;

  zoneSelection = new MySelection<Zone>('id');
  softSelection = new MySelection<SoftwareInfo>('id');
  softDataSource = this.statisticService.areaSoftware();
  zoneIDs = [];
  user = this.loginService.User$.toPromise();

  selectChange$ = new ReplaySubject(1);
  upgrade$ = this.selectChange$.pipe(
    switchMap((opt: { zones: number[]; apps: number[] }) => {
      return this.statisticService.softwareUsage({
        period: 'month',
        soft_ids: opt.apps,
        area_ids: opt.zones,
      });
    }),
    map(data => {
      let arr = _.map(data.usage_num, v => ({ name: v.name, value: v.number }));
      if (data.software_num > 0 && data.software_num < 6) {
        return arr;
      }
      arr = arr.sort((a, b) => b.value - a.value).slice(0, 5);
      const count = arr.reduce((acc, a) => (acc += a.value), 0);
      arr.push({ name: '其他', value: data.total - count });
      return arr;
    }),
  );
  ngOnInit() {
    this.init();
  }

  async storeKey() {
    const user = await this.user;
    const zid = this.zone ? this.zone.id : -1;
    return `${user.uid}_${StoreKey}_${zid}`;
  }

  async init() {
    let opt = { zones: [], apps: [] };
    const key = await this.storeKey();
    const value = localStorage.getItem(key);
    if (value) {
      opt = JSON.parse(value);
    }
    if (this.zone) {
      this.zoneSelection.select({ id: this.zone.id } as any);
      opt.zones = [this.zone.id];
      this.zoneIDs = [this.zone.id];
    }
    this.selectChange$.next(opt);
    setTimeout(() => {
      this.chart.setOption(defaultOption);
      this.upgrade$.subscribe(data => {
        this.chart.setOption({ series: [{ data: [{ ...data[0] }, ...data.slice(1)] }] });
      });
    });
  }

  zoneChange() {
    this.zoneIDs = this.zoneSelection.selected.map(e=>e.area_id);
    if (!this.zoneIDs.length) {
      this.confirm();
      return;
    }
    this.dialog.open(this.softwareSelect);
  }

  async confirm() {
    this.dialog.closeAll();
    const option = {
      zones: this.zoneSelection.keys(),
      apps: this.softSelection.keys(),
    };
    const key = await this.storeKey();
    localStorage.setItem(key, JSON.stringify(option));
    this.selectChange$.next(option);
  }
}

const defaultShowLabel = {
  label: {
    normal: {
      show: true,
    },
  },
};
const defaultOption: EChartOptionExp = {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
  },
  // 图例
  legend: {
    orient: 'vertical',
    x: 'right',
    y: 'center',
  },
  series: [
    {
      name: '软件使用率',
      type: 'pie',
      center: ['30%', '50%'],
      label: {
        normal: {
          show: false,
          formatter: '{d}%',
        },
        emphasis: {
          show: true,
          formatter: '{d}%',
        },
      },
    },
  ],
};
